<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="批次号" prop="batchNo">
        <el-input v-model="queryParams.batchNo" clearable @keyup.enter.native="handleQuery" placeholder="请输入批次号"/>
      </el-form-item>
      <el-form-item label="物料名称" prop="materialName">
        <el-input v-model="queryParams.material.materialName" clearable @keyup.enter.native="handleQuery"
                  placeholder="请输入物料名称"/>
      </el-form-item>
      <!--        :props="{-->
      <!--          value:'value',-->
      <!--          label:'label',-->
      <!--          children:'children',-->
      <!--          checkStrictly:true-->
      <!--        }"-->
      <el-form-item label="请选择所属仓库和库区" label-width="160px" prop="selectedWarehouseStorageArea">
        <el-cascader
          style=""
          v-model="selectedWarehouseStorageArea"
          :options="WarehouseStorageAreaOptions"
          @change="handleWarehouseStorageAreaChange"
          clearable
          @keyup.enter.native="handleQuery"
          :props="{
                    checkStrictly:true
        }"
        ></el-cascader>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态">
          <el-option label="全部" value=""/>
          <el-option label="正常" value="1"/>
          <el-option label="待检" value="2"/>
          <el-option label="不良品" value="3"/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!--      <el-col :span="1.5">-->
      <!--        <el-button-->
      <!--          type="primary"-->
      <!--          plain-->
      <!--          icon="el-icon-plus"-->
      <!--          size="mini"-->
      <!--          @click="handleAdd"-->
      <!--          v-hasPermi="['storage:inventory:add']"-->
      <!--        >新增</el-button>-->
      <!--      </el-col>-->
      <!--      <el-col :span="1.5">-->
      <!--        <el-button-->
      <!--          type="success"-->
      <!--          plain-->
      <!--          icon="el-icon-edit"-->
      <!--          size="mini"-->
      <!--          :disabled="single"-->
      <!--          @click="handleUpdate"-->
      <!--          v-hasPermi="['storage:inventory:edit']"-->
      <!--        >修改</el-button>-->
      <!--      </el-col>-->
      <!--      <el-col :span="1.5">-->
      <!--        <el-button-->
      <!--          type="danger"-->
      <!--          plain-->
      <!--          icon="el-icon-delete"-->
      <!--          size="mini"-->
      <!--          :disabled="multiple"-->
      <!--          @click="handleDelete"-->
      <!--          v-hasPermi="['storage:inventory:remove']"-->
      <!--        >删除</el-button>-->
      <!--      </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['storage:inventory:export']"
        >导出
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-refresh"
          size="mini"
          @click="handleRefresh"
        >刷新库存
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="inventoryList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="批次号" prop="batchNo" align="center"/>
      <el-table-column label="物料名称" prop="material.materialName" align="center"/>
      <el-table-column label="所属仓库" prop="warehouse.name" align="center"/>
      <el-table-column label="所属库区" prop="storageArea.name" align="center"/>
      <el-table-column label="库存数量" prop="quantity" align="center"/>
      <el-table-column label="锁定数量" prop="lockedQuantity" align="center"/>
      <el-table-column label="单位" prop="unit" align="center"/>
      <el-table-column label="状态" prop="status" align="center" :formatter="formatInventoryStatus"/>
      <el-table-column label="详细数据" type="expand" align="center" width="100px">
        <template #default="props">
          <el-descriptions style="padding: 0 100px">
            <el-descriptions-item label="生产日期">{{ props.row.productionDate }}</el-descriptions-item>
            <el-descriptions-item label="过期时间">{{ props.row.expiryDate }}</el-descriptions-item>
          </el-descriptions>
          <el-descriptions style="padding: 0 100px">
            <el-descriptions-item label="创建时间">{{ props.row.createdAt }}</el-descriptions-item>
            <el-descriptions-item label="更新时间">{{ props.row.updatedAt }}</el-descriptions-item>
          </el-descriptions>
        </template>
      </el-table-column>
      <!--      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">-->
      <!--        <template slot-scope="scope">-->
      <!--          <el-button-->
      <!--            size="mini"-->
      <!--            type="text"-->
      <!--            icon="el-icon-edit"-->
      <!--            @click="handleUpdate(scope.row)"-->
      <!--            v-hasPermi="['storage:inventory:edit']"-->
      <!--          >修改</el-button>-->
      <!--          <el-button-->
      <!--            size="mini"-->
      <!--            type="text"-->
      <!--            icon="el-icon-delete"-->
      <!--            @click="handleDelete(scope.row)"-->
      <!--            v-hasPermi="['storage:inventory:remove']"-->
      <!--          >删除</el-button>-->
      <!--        </template>-->
      <!--      </el-table-column>-->
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改库存管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {listInventory, getInventory, delInventory, addInventory, updateInventory} from "@/api/storage/inventory"
import Dept from "@/views/system/dept/index.vue";
import Operlog from "@/views/monitor/operlog/index.vue";
import {getErpWarehouseAndArea} from "@/api/storage/warehouse";
import eventBus from "@/utils/eventBus";

export default {
  name: "Inventory",
  components: {Operlog, Dept},
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 库存管理表格数据
      inventoryList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        material: {
          materialName: ''
        },
      },
      // 存储仓库库区数据
      WarehouseStorageAreaOptions: [],
      // 存储选择的仓库和库区信息
      selectedWarehouseStorageArea: [],
      // 表单参数
      form: {},
      // 表单校验
      rules: {}
    }
  },
  created() {
    this.getList()
    this.loadWarehouseStorageAreaOptions()
    
    // 监听库存刷新事件
    eventBus.$on('refresh-inventory', this.handleInventoryRefresh)
  },
  
  beforeDestroy() {
    // 组件销毁前移除事件监听
    eventBus.$off('refresh-inventory', this.handleInventoryRefresh)
  },
  methods: {
    // 处理库存刷新事件
    handleInventoryRefresh() {
      console.log('收到库存刷新事件，正在刷新库存数据...')
      this.getList()
    },
    
    //格式化库存状态的显示
    formatInventoryStatus(row) {
      const statusMap = {
        1: '正常',
        2: '待检',
        3: '不良品',
      };
      return statusMap[row.status] || row.status;
    },

    /** 查询库存管理列表 */
    getList() {
      this.loading = true
      const params = this.buildQueryParamsForApi()
      listInventory(params).then(response => {
        let rows = response.rows || []
        // 兜底：后端若未按名称过滤成功，则前端再按 material.materialName 包含匹配（不区分大小写）
        const keyword = (this.queryParams.material && this.queryParams.material.materialName) ? String(this.queryParams.material.materialName).trim() : ''
        if (keyword) {
          const kw = keyword.toLowerCase()
          rows = rows.filter(item => {
            const name = item && item.material && item.material.materialName ? String(item.material.materialName) : ''
            return name.toLowerCase().includes(kw)
          })
        }
        this.inventoryList = rows
        this.total = keyword ? rows.length : response.total
        this.loading = false
      })
    },
    // 构造后端期望的查询参数：将嵌套 material.materialName 改为点号键名，避免方括号序列化导致后端取不到
    buildQueryParamsForApi() {
      const qp = { ...this.queryParams }
      const materialName = (qp.material && qp.material.materialName) ? String(qp.material.materialName).trim() : ''
      delete qp.material
      if (materialName) {
        // 同时兼容两种风格：点号 & 中括号，避免后端绑定差异导致条件失效
        qp['material.materialName'] = materialName
        qp['material[materialName]'] = materialName
      }
      // 其他空值清理，避免发送空字符串影响后端判空
      if (qp.batchNo !== undefined && qp.batchNo !== null) {
        const v = String(qp.batchNo).trim()
        if (v === '') delete qp.batchNo; else qp.batchNo = v
      }
      if (qp.status !== undefined && qp.status !== null && qp.status === '') {
        delete qp.status
      }
      return qp
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        materialId: null,
        warehouseId: null,
        areaId: null,
        batchNo: null,
        quantity: null,
        lockedQuantity: null,
        unit: null,
        productionDate: null,
        expiryDate: null,
        status: null,
        createdAt: null,
        updatedAt: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    // 加载仓库库区级联选择器数据
    loadWarehouseStorageAreaOptions() {
      try {
        this.loading = true
        getErpWarehouseAndArea().then(response => {
          this.WarehouseStorageAreaOptions = response
        })
        this.loading = false
      } catch (error) {
        this.$message.error("加载仓库库区数据失败")
      }
    },
    // 监听仓库库区级联选择器的变化
    handleWarehouseStorageAreaChange(selectedValues) {
      this.queryParams.warehouseId = selectedValues[0]
      this.queryParams.areaId = selectedValues[1]
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.selectedWarehouseStorageArea = []
      this.queryParams.warehouseId = ''
      this.queryParams.areaId = ''
      this.resetForm("queryForm")
      this.handleQuery()

    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加库存管理"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getInventory(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改库存管理"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateInventory(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
              
              // 发送库存刷新事件，通知其他相关页面刷新数据
              eventBus.$emit('refresh-inventory');
            })
          } else {
            addInventory(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
              
              // 发送库存刷新事件，通知其他相关页面刷新数据
              eventBus.$emit('refresh-inventory');
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除库存管理编号为"' + ids + '"的数据项？').then(function () {
        return delInventory(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      const params = this.buildQueryParamsForApi()
      this.download('storage/inventory/export', {
        ...params
      }, `inventory_${new Date().getTime()}.xlsx`)
    },
    /** 刷新库存按钮操作 */
    handleRefresh() {
      this.getList()
      this.$message.success("库存数据已刷新")
    }
  }
}
</script>
